/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package se.bth.ke.firstfriend.web;

import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.UniformInterfaceException;
import com.sun.jersey.api.representation.Form;
import com.sun.jersey.client.apache.config.DefaultApacheHttpClientConfig;
import com.sun.jersey.test.framework.JerseyTest;
import com.sun.jersey.test.framework.WebAppDescriptor;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ws.rs.core.MediaType;
import se.bth.ke.firstfriend.model.Article;

/**
 *
 * @author nico
 */
public class Base extends JerseyTest {

    private static WebAppDescriptor APP_DESCRIPTOR;

    static {
        Logger.getLogger("org.hibernate").setLevel(Level.WARNING);
    }

    public Base() {
        super(getAppDescriptor());
    }

    public static WebAppDescriptor getAppDescriptor() {
        if (APP_DESCRIPTOR == null) {
            APP_DESCRIPTOR = new WebAppDescriptor.Builder("se.bth.ke.firstfriend", "de.nixis.base")
                .filterClass(com.sun.jersey.spi.spring.container.servlet.SpringServlet.class)
                .addFilter(de.nixis.commons.sitemesh.SiteMeshDecoratorFilter.class, "SitemeshDecoratorFilter")
                .contextListenerClass(org.springframework.web.context.ContextLoaderListener.class)
                .requestListenerClass(org.springframework.web.context.request.RequestContextListener.class)
                .clientConfig(new DefaultApacheHttpClientConfig())
                .contextParam("contextConfigLocation", "classpath:spring-test.xml")
                .initParam("com.sun.jersey.config.property.JSPTemplatesBasePath", "/WEB-INF/views")
                .initParam("com.sun.jersey.config.property.WebPageContentRegex", "/(images|style|scripts)/.*")
                .initParam("com.sun.jersey.spi.container.ContainerRequestFilters", "se.bth.ke.firstfriend.security.SecurityFilter")
                .initParam("com.sun.jersey.spi.container.ResourceFilters", "com.sun.jersey.api.container.filter.RolesAllowedResourceFilterFactory")
                .build();
        }
        
        return APP_DESCRIPTOR;
    }


    public void setupTestEnvironment() {

    }

    public void addArticle(Article article, String topics) {

        Form f = new Form();
        f.add("title", article.getTitle());
        f.add("topics", topics);
        f.add("content", article.getContent());

        // Fix for redirect bug in jersey or HttpURLConnection impl
        client().setFollowRedirects(false);

        try {
            resource()
                    .path("/article")
                    .accept(MediaType.APPLICATION_XML).post(f);
        } catch (UniformInterfaceException e) {
            if (e.getResponse().getClientResponseStatus() !=
                    ClientResponse.Status.SEE_OTHER) {
                throw e;
            }
        }

        client().setFollowRedirects(true);
    }
}
